//应用程序相关全局通用方法和数据
import Cookies from 'js-cookie'

const state = {
  //侧边栏信息
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false,
    hide: false
  },
  //当前设备
  device: 'desktop',
  //显示大小
  size: Cookies.get('size') || 'medium'
}

//mutations是Vuex中唯一允许更新应用状态的函数，是同步函数
const mutations = {
  /**
   * 切换侧边栏
   * @param state
   * @returns {boolean}
   * @constructor
   */
  TOGGLE_SIDEBAR: state => {
    if (state.sidebar.hide) {
      return false;
    }
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  /**
   * 关闭侧边栏
   * @param state
   * @param withoutAnimation
   * @constructor
   */
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  /**
   * 切换设备
   * @param state
   * @param device
   * @constructor
   */
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  /**
   * 设置显示大小
   * @param state
   * @param size
   * @constructor
   */
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  },
  /**
   * 设置侧边栏是否隐藏
   * @param state
   * @param status
   * @constructor
   */
  SET_SIDEBAR_HIDE: (state, status) => {
    state.sidebar.hide = status
  }
}

//actions是Vuex中处理异步操作的函数，它们不能直接修改状态，而是通过调用 mutations 来间接修改状态
const actions = {
  /**
   * 切换侧边栏
   * @param commit
   */
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  /**
   * 关闭侧边栏
   * @param commit
   * @param withoutAnimation
   */
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  /**
   * 切换设备
   * @param commit
   * @param device
   */
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  /**
   * 设置显示大小
   * @param commit
   * @param size
   */
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },
  /**
   * 设置侧边栏是否隐藏
   * @param commit
   * @param status
   */
  toggleSideBarHide({ commit }, status) {
    commit('SET_SIDEBAR_HIDE', status)
  }
}

export default {
  // 必须加模块名前缀
  namespaced: true,
  state,
  mutations,
  actions
}
